﻿using Newtonsoft.Json.Linq;
using PPSMS.CommonForm;
using PPSMS.Controllers;
using PPSMS_BLL;
using PPSMS_Model;
using Sunny.UI;
using System.Data;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Excel;

namespace PPSMS
{
    public partial class DataStatisticsForm : UIPage
    {

        StationStatistics_BLL stationStatistics_BLL = new StationStatistics_BLL();

        private event Action<DateTime> ShowMessageChange;

        public static event Action<System.Data.DataTable, string>? SelectChange;

        private ChartForm chartForm = new ChartForm();

        public static System.Data.DataTable dt = new System.Data.DataTable();

        public DataStatisticsForm()
        {
            InitializeComponent();
        }

        private void DataLoad()
        {
            System.Data.DataTable dt1 = new System.Data.DataTable();
            dt1.Columns.Add("ID", typeof(int));
            dt1.Columns.Add("DATE", typeof(string));
            dt1.Columns.Add("TOTAL_ENERGY_PRODUCED", typeof(double));
            dt1.Columns.Add("TOTAL_REVENUE", typeof(double));
            dt1.Columns.Add("CO2_REDUCTION", typeof(double));
            foreach (StationStatistics stationStatistics in stationStatistics_BLL.SelectAll())
            {
                dt1.Rows.Add(stationStatistics.ID, stationStatistics.Date, stationStatistics.TotalEnergyProduced, stationStatistics.TotalRevenue, stationStatistics.Co2Reduction);
            }
            this.uiDataGridView1.DataSource = dt1;
            dt = dt1;
        }

        private void DataStatisticsForm_Load(object sender, EventArgs e)
        {
            //DataLoad();
            this.uiButton1.FillColor =Color.DarkSlateGray;
           DatePickerChange(this.uiDatePicker1.Value);
            ShowMessageChange += (t) => DatePickerChange(t);
            ChartForm.ButtonColor += (q) => { this.uiSymbolButton1.FillColor = q; };
        }

        private void uiSymbolButton1_Click(object sender, EventArgs e)
        {
            //this.uiDataGridView1.Visible = this.uiDataGridView1.Visible ? false : true;
            this.uiSymbolButton1.FillColor = this.uiSymbolButton1.FillColor == Color.DarkSlateGray ? UIColor.LayuiBlue : Color.DarkSlateGray;
            if (this.uiSymbolButton1.FillColor == Color.DarkSlateGray)
            {
                if (chartForm.IsDisposed)
                {
                    chartForm = new ChartForm();
                }
                chartForm.Show();
            }
            else
            {
                chartForm.Close();
            }

            ChartInvoke();
        }

        private void ClinkSelect(UIButton uIButton, string da)
        {
            this.uiButton1.FillColor = this.uiButton2.FillColor = this.uiButton3.FillColor = UIColor.LayuiBlue;
            this.uiSymbolButton4.Text = $"上一{da}";
            this.uiSymbolButton5.Text = $"下一{da}";
            if (da == "日")
            {
                this.uiDatePicker1.DateFormat = "yyyy-MM-dd";
            }
            else if (da == "月")
            {
                this.uiDatePicker1.DateFormat = "yyyy-MM";
            }
            else if (da == "年")
            {
                this.uiDatePicker1.DateFormat = "yyyy";
            }
            uIButton.FillColor = uIButton.FillColor == Color.DarkSlateGray ? UIColor.LayuiBlue : Color.DarkSlateGray;
        }

        private void uiButton1_Click(object sender, EventArgs e)
        {
            ClinkSelect(sender as UIButton, "日");
        }

        private void uiButton2_Click(object sender, EventArgs e)
        {
            ClinkSelect(sender as UIButton, "月");
        }

        private void uiButton3_Click(object sender, EventArgs e)
        {
            ClinkSelect(sender as UIButton, "年");
        }

        private void uiSymbolButton4_Click(object sender, EventArgs e)
        {
            DatePickerChange(-1);
        }

        private void DatePickerChange(int a)
        {
            if (this.uiDatePicker1.DateFormat == "yyyy-MM-dd")
            {
                this.uiDatePicker1.Value = this.uiDatePicker1.Value.AddDays(a);
            }
            else if (this.uiDatePicker1.DateFormat == "yyyy-MM")
            {
                this.uiDatePicker1.Value = this.uiDatePicker1.Value.AddMonths(a);
            }
            else if (this.uiDatePicker1.DateFormat == "yyyy")
            {
                this.uiDatePicker1.Value = this.uiDatePicker1.Value.AddYears(a);
            }
        }

        private void uiSymbolButton5_Click(object sender, EventArgs e)
        {
            DatePickerChange(1);
        }

        private void uiDatePicker1_ValueChanged(object sender, DateTime value)
        {
            DatePickerChange(value);
        }

        private void DatePickerChange(DateTime value)
        {
            string date = value.ToString(this.uiDatePicker1.DateFormat);
            if (date == "") return;
            date = date.Replace("/", "-");
            if (date.Length <= 7)
            {
                dt = stationStatistics_BLL.SelectByDatesBLL(date,
            this.uiTabControl1.SelectedTab.Name);
            }
            else
            {
                dt = stationStatistics_BLL.SelectByDateBLL(date, this.uiTabControl1.SelectedTab.Name);
            }
            if (this.uiTabControl1.SelectedTab.Name == "STATION_STATISTICS")
            {
                this.uiDataGridView1.DataSource = dt;
            }
            else
            {
                this.uiDataGridView2.DataSource = dt;
            }
        }

        private void uiTabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            ShowMessageChange?.Invoke(this.uiDatePicker1.Value);
        }

        private void uiDataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            ChartInvoke();
        }

        private void ChartInvoke()
        {
            if (this.uiDataGridView1.SelectedRows.Count > 0 && this.uiTabControl1.SelectedTab.Name == "STATION_STATISTICS")
            {
                string name = this.uiTabControl1.SelectedTab.Name;
                SelectChange?.Invoke(dt, name);
            }
            else if (this.uiDataGridView2.SelectedRows.Count > 0 && this.uiTabControl1.SelectedTab.Name == "INVERTER_STATISTICS")
            {
                string name = this.uiTabControl1.SelectedTab.Name;
                SelectChange?.Invoke(dt, name);
            }
        }

        private void uiDataGridView2_SelectionChanged(object sender, EventArgs e)
        {
            ChartInvoke();
        }

        private void uiSymbolButton2_Click(object sender, EventArgs e)
        {
            if (this.uiDataGridView1.SelectedRows.Count <= 0) { MessageBox.Show("数据为空，无法保存"); return; }
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Excel Files|*.xlsx";
            saveFileDialog.Title = "Save Excel File";
            saveFileDialog.InitialDirectory = @"E:\1-2407\项目资料\PPSMS";
            saveFileDialog.FileName = "数据记录.xlsx";
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    // 创建 Excel 应用程序对象
                    Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();

                    // 创建一个新的工作簿
                    Workbook workbook = excelApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);

                    // 获取活动工作表
                    Worksheet worksheet = workbook.ActiveSheet;
                    if (this.uiTabControl1.SelectedTab.Name == "STATION_STATISTICS")
                    {
                        worksheet.Name = "电站数据统计图表";
                        worksheet.Cells[1, 1] = "日期";
                        worksheet.Cells[1, 2] = "电站累计发电量";
                        worksheet.Cells[1, 3] = "电站累计收入";
                        worksheet.Cells[1, 4] = "累计二氧化碳减排";
                        worksheet.Cells[1, 5] = "ID";
                    }
                    else if (this.uiTabControl1.SelectedTab.Name == "INVERTER_STATISTICS")
                    {
                        worksheet.Name = "逆变器数据统计图表";
                        worksheet.Cells[1, 1] = "逆变器ID";
                        worksheet.Cells[1, 2] = "日期";
                        worksheet.Cells[1, 3] = "日发电量/kW·h ";
                        worksheet.Cells[1, 4] = "累计发电量/kW·h";
                        worksheet.Cells[1, 5] = "累计二氧化碳减排";
                        worksheet.Cells[1, 1] = "ID";
                    }

                    // 写入数据
                    System.Data.DataTable dtable = dt;
                    for (int i = 0; i < dtable.Rows.Count; i++)
                    {
                        for (int j = 0; j < dtable.Columns.Count; j++)
                        {
                            worksheet.Cells[i + 2, j + 1] = dtable.Rows[i][j];
                        }
                    }

                    // 保存文件
                    workbook.SaveAs(saveFileDialog.FileName);

                    // 关闭 Excel 应用程序
                    workbook.Close(false, Type.Missing, Type.Missing);
                    excelApp.Quit();

                    MessageBox.Show("Excel 文件已成功创建");

                    // 清理 COM 对象
                    Marshal.ReleaseComObject(worksheet);
                    Marshal.ReleaseComObject(workbook);
                    Marshal.ReleaseComObject(excelApp);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("创建 Excel 文件时发生错误: " + ex.Message);
                }
            }
        }

        private void uiDatePicker1_TextChanged(object sender, EventArgs e)
        {
            DatePickerChange(this.uiDatePicker1.Value);
        }
    }
}
